<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>咖啡购买 - 猫咖管理系统</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        /* 全局样式 */
        :root {
            --primary-color: #D85D5D;
            --secondary-color: #9B7E46;
            --accent-color: #FFA384;
            --light-color: #F8F3EA;
            --dark-color: #333333;
            --success-color: #4CAF50;
            --error-color: #FF5252;
            --transition: all 0.3s ease;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f9f9f9;
            color: var(--dark-color);
            line-height: 1.6;
        }

        .container {
            width: 100%;
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
        }

        /* 顶部导航栏样式 */
        header {
            background-color: white;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            position: sticky;
            top: 0;
            z-index: 1000;
        }

        .header-container {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px 0;
        }

        .logo {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .logo-icon {
            width: 40px;
            height: 40px;
            background-color: var(--primary-color);
            border-radius: 50%;
            position: relative;
        }

        .logo-icon::after {
            content: '';
            position: absolute;
            top: -4px;
            left: -4px;
            width: 48px;
            height: 48px;
            border-radius: 50%;
            border: 1px solid rgba(93, 126, 216, 0.2);
        }

        .logo h1 {
            font-size: 24px;
            color: var(--primary-color);
        }

        nav ul {
            display: flex;
            list-style: none;
            gap: 25px;
        }

        nav a {
            text-decoration: none;
            color: var(--dark-color);
            font-weight: 500;
            padding: 8px 12px;
            border-radius: 4px;
            transition: var(--transition);
            position: relative;
        }

        nav a:hover,
        nav a.active {
            color: var(--primary-color);
        }

        nav a::after {
            content: '';
            position: absolute;
            bottom: -5px;
            left: 0;
            width: 0;
            height: 2px;
            background-color: var(--primary-color);
            transition: var(--transition);
        }

        nav a:hover::after,
        nav a.active::after {
            width: 100%;
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .user-info span {
            font-weight: 500;
        }

        .btn {
            padding: 8px 16px;
            border-radius: 4px;
            border: none;
            cursor: pointer;
            font-weight: 500;
            transition: var(--transition);
        }

        .btn-primary {
            background-color: var(--primary-color);
            color: white;
        }

        .btn-primary:hover {
            background-color: #4a68c5;
        }

        .btn-outline {
            background-color: transparent;
            border: 1px solid var(--primary-color);
            color: var(--primary-color);
        }

        .btn-outline:hover {
            background-color: var(--primary-color);
            color: white;
        }

        /* 搜索区域 */
        .search-section {
            background-color: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
            margin: 30px 0;
        }

        .search-container {
            display: flex;
            gap: 15px;
            margin-bottom: 20px;
        }

        .search-box {
            flex: 1;
            position: relative;
        }

        .search-box input {
            width: 100%;
            padding: 12px 20px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
            transition: var(--transition);
        }

        .search-box input:focus {
            border-color: var(--primary-color);
            outline: none;
            box-shadow: 0 0 0 3px rgba(93, 126, 216, 0.2);
        }

        .search-box i {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: #999;
        }

        .categories {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 15px;
        }

        .category-btn {
            padding: 8px 16px;
            background-color: #f0f0f0;
            border: none;
            border-radius: 20px;
            cursor: pointer;
            transition: var(--transition);
        }

        .category-btn:hover,
        .category-btn.active {
            background-color: var(--primary-color);
            color: white;
        }

        /* 咖啡列表样式 */
        .main-content {
            padding: 20px 0 60px;
        }

        .section-title {
            text-align: center;
            margin-bottom: 40px;
            position: relative;
        }

        .section-title h2 {
            font-size: 32px;
            color: var(--primary-color);
            display: inline-block;
            margin-bottom: 15px;
        }

        .section-title::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 80px;
            height: 3px;
            background-color: var(--secondary-color);
        }

        .coffees-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 30px;
        }

        .coffee-card {
            background-color: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
            transition: var(--transition);
            cursor: pointer;
        }

        .coffee-card:hover {
            transform: translateY(-10px);
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
        }

        .coffee-image {
            height: 200px;
            width: 100%;
            background-size: cover;
            background-position: center;
            position: relative;
        }

        .coffee-price {
            position: absolute;
            bottom: 10px;
            right: 10px;
            background-color: var(--primary-color);
            color: white;
            padding: 5px 10px;
            border-radius: 4px;
            font-weight: bold;
            font-size: 18px;
        }

        .coffee-info {
            padding: 15px;
        }

        .coffee-info h3 {
            font-size: 20px;
            margin-bottom: 5px;
            color: var(--dark-color);
        }

        .coffee-info .coffee-category {
            color: var(--secondary-color);
            font-weight: 500;
            margin-bottom: 10px;
            display: block;
        }

        .coffee-info p {
            color: #666;
            font-size: 14px;
            height: 40px;
            overflow: hidden;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
        }

        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.7);
            z-index: 2000;
            overflow-y: auto;
            padding: 20px;
        }

        .modal-content {
            background-color: white;
            max-width: 800px;
            margin: 40px auto;
            border-radius: 8px;
            overflow: hidden;
            position: relative;
        }

        .close-modal {
            position: absolute;
            top: 15px;
            right: 15px;
            width: 30px;
            height: 30px;
            background-color: rgba(0, 0, 0, 0.3);
            color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            z-index: 10;
            font-size: 18px;
            transition: var(--transition);
        }

        .close-modal:hover {
            background-color: var(--primary-color);
        }

        .coffee-detail {
            display: flex;
            flex-direction: column;
        }

        @media (min-width: 768px) {
            .coffee-detail {
                flex-direction: row;
            }
        }

        .detail-image {
            flex: 1;
            height: 400px;
            background-size: cover;
            background-position: center;
            position: relative;
            cursor: zoom-in;
        }

        .detail-image.zoomed {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 3000;
            cursor: zoom-out;
            background-size: contain;
            background-repeat: no-repeat;
            background-position: center;
        }

        .detail-info {
            flex: 1;
            padding: 30px;
        }

        .detail-info h2 {
            font-size: 28px;
            margin-bottom: 10px;
            color: var(--primary-color);
        }

        .coffee-meta {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;
        }

        .meta-item {
            display: flex;
            flex-direction: column;
        }

        .meta-label {
            font-size: 14px;
            color: #999;
        }

        .meta-value {
            font-weight: 500;
            font-size: 18px;
        }

        .detail-description {
            margin: 20px 0;
            line-height: 1.8;
        }

        .order-form {
            background-color: var(--light-color);
            padding: 20px;
            border-radius: 8px;
            margin-top: 20px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
        }

        .form-group input, .form-group select {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
        }

        /* 页脚样式 */
        footer {
            background-color: var(--dark-color);
            color: white;
            padding: 40px 0 20px;
        }

        .footer-content {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 30px;
            margin-bottom: 30px;
        }

        .footer-column h3 {
            font-size: 20px;
            margin-bottom: 20px;
            position: relative;
            padding-bottom: 10px;
        }

        .footer-column h3::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            width: 50px;
            height: 2px;
            background-color: var(--primary-color);
        }

        .footer-links {
            list-style: none;
        }

        .footer-links li {
            margin-bottom: 10px;
        }

        .footer-links a {
            color: #bbb;
            text-decoration: none;
            transition: var(--transition);
        }

        .footer-links a:hover {
            color: white;
            padding-left: 5px;
        }

        .contact-info {
            color: #bbb;
        }

        .contact-info p {
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .copyright {
            text-align: center;
            padding-top: 20px;
            border-top: 1px solid #444;
            color: #bbb;
            font-size: 14px;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .header-container {
                flex-direction: column;
                gap: 15px;
            }

            nav ul {
                flex-wrap: wrap;
                justify-content: center;
            }

            .search-container {
                flex-direction: column;
            }

            .coffee-detail {
                flex-direction: column;
            }

            .detail-image {
                height: 300px;
            }
        }

        /* 加载动画 */
        .loader {
            text-align: center;
            padding: 40px;
            display: none;
        }

        .loader .spinner {
            border: 4px solid rgba(0, 0, 0, 0.1);
            border-radius: 50%;
            border-top: 4px solid var(--primary-color);
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 20px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 25px;
            border-radius: 4px;
            color: white;
            font-weight: 500;
            z-index: 3000;
            opacity: 0;
            transform: translateX(100%);
            transition: all 0.3s ease;
        }

        .notification.success {
            background-color: var(--success-color);
            opacity: 1;
            transform: translateX(0);
        }

        .notification.error {
            background-color: var(--error-color);
            opacity: 1;
            transform: translateX(0);
        }

        .quantity-control {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 20px;
        }

        .quantity-btn {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            background: var(--primary-color);
            color: white;
            border: none;
            font-size: 18px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .quantity-input {
            width: 60px;
            text-align: center;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
        }

        /* 添加咖啡模态框样式 */
        #add-coffee-modal .modal-content {
            max-width: 600px;
            margin: 40px auto;
            border-radius: 8px;
            overflow: hidden;
            position: relative;
        }

        #add-coffee-modal h2 {
            text-align: center;
            padding: 20px;
            font-size: 24px;
            color: var(--primary-color);
            background-color: var(--light-color);
            margin: 0;
            border-bottom: 1px solid #eee;
        }

        #add-coffee-modal .detail-image {
            height: 200px;
            cursor: pointer;
            background-color: #f8f9fa;
            border: 2px dashed #ccc;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
            margin: 0 20px;
            margin-top: 20px;
        }

        #add-coffee-modal .detail-image:hover {
            border-color: var(--primary-color);
        }

        #add-coffee-modal .upload-icon {
            font-size: 36px;
            color: #aaa;
            opacity: 0.6;
            transition: all 0.3s ease;
        }

        #add-coffee-modal .detail-image:hover .upload-icon {
            opacity: 1;
        }

        #add-coffee-modal .detail-image img {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
        }

        #add-coffee-modal #coffee-image-name {
            text-align: center;
            font-size: 12px;
            color: #666;
            margin-top: 5px;
        }

        #add-coffee-modal .detail-info {
            width: 100%;
            padding: 20px;
        }

        #add-coffee-modal .form-group {
            margin-bottom: 20px;
        }

        #add-coffee-modal label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
        }

        #add-coffee-modal input,
        #add-coffee-modal select,
        #add-coffee-modal textarea {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
        }

        #add-coffee-modal .error-text {
            color: var(--error-color);
            font-size: 13px;
            margin-top: 5px;
            display: none;
        }

        #add-coffee-modal .form-group.error .error-text {
            display: block;
        }

        #add-coffee-modal .form-group.error input,
        #add-coffee-modal .form-group.error select,
        #add-coffee-modal .form-group.error textarea {
            border-color: var(--error-color);
        }

        .detail-image {
            flex: 1;
            height: 400px;
            background-size: cover;
            background-position: center;
            position: relative;
            transition: background-size 0.3s ease, background-position 0.3s ease;
        }


    </style>
</head>
<body>
<!-- 顶部导航栏 -->
<header>
    <div class="container header-container">
        <div class="logo">
            <div class="logo-icon"></div>
            <h1>猫咖管理系统</h1>
        </div>

        <nav>
            <ul>
                <li><a href="index.html">首页</a></li>
                <li><a href="cat.html">猫咪预约</a></li>
                <li><a href="cafe.html" class="active">咖啡购买</a></li>
                <li><a href="center.html">个人中心</a></li>
                <li><a href="message.html">留言板</a></li>
<!--                <li><a href="shoppingcart.html">购物车</a></li>-->
                <li><a href="orders.html">订单信息</a></li>
                <li><a href="booking.html">预约信息</a></li>
            </ul>
        </nav>

        <!-- 顶部导航栏的用户信息部分 -->
        <div class="user-info">
            <span id="user-display">未登录</span>
            <button class="btn btn-primary" id="logout-btn">退出</button>
        </div>
    </div>
</header>

<!-- 搜索区域 -->
<section class="search-section">
    <div class="container">
        <div class="search-container">
            <div class="search-box">
                <input type="text" id="search-input" placeholder="搜索咖啡名字...">
                <i class="fas fa-search"></i>
            </div>
            <button class="btn btn-primary" id="search-btn">搜索</button>
            <button class="btn btn-outline" id="reset-btn">重置</button>
            <button class="btn btn-primary" id="add-coffee-btn">新增咖啡</button>
        </div>

        <div class="categories">
            <button class="category-btn active" data-category="all">全部</button>
            <button class="category-btn" data-category="浓缩咖啡">浓缩咖啡</button>
            <button class="category-btn" data-category="拿铁">拿铁</button>
            <button class="category-btn" data-category="卡布奇诺">卡布奇诺</button>
            <button class="category-btn" data-category="美式咖啡">美式咖啡</button>
            <button class="category-btn" data-category="摩卡">摩卡</button>
            <button class="category-btn" data-category="冷萃">冷萃</button>
        </div>
    </div>
</section>

<!-- 主要内容区域 -->
<section class="main-content">
    <div class="container">
        <div class="section-title">
            <h2>精选咖啡</h2>
            <p>选择您喜欢的咖啡进行下单</p>
        </div>

        <div class="loader">
            <div class="spinner"></div>
            <p>正在加载咖啡信息...</p>
        </div>

        <div class="coffees-grid" id="coffees-grid">
            <!-- 咖啡卡片将通过JS动态生成 -->
        </div>
    </div>
</section>

<!-- 咖啡详情模态框 -->
<div class="modal" id="coffee-modal">
    <div class="modal-content">
        <div class="close-modal" id="close-modal">
            <i class="fas fa-times"></i>
        </div>
        <div class="coffee-detail">
            <div class="detail-image" id="detail-image"></div>
            <div class="detail-info">
                <h2 id="detail-name">咖啡名称</h2>
                <div class="coffee-meta">
                    <div class="meta-item">
                        <span class="meta-label">分类</span>
                        <span class="meta-value" id="detail-category">未知</span>
                    </div>
                    <div class="meta-item">
                        <span class="meta-label">价格</span>
                        <span class="meta-value" id="detail-price">未知</span>
                    </div>
                </div>

                <p class="detail-description" id="detail-description">
                    咖啡描述信息将显示在这里...
                </p>

                <div class="order-form">
                    <h3>下单信息</h3>
                    <div class="form-group">
                        <label for="coffee-flavor">口味选择</label>
                        <select id="coffee-flavor">
                            <option value="">请选择口味</option>
                            <option value="原味">原味</option>
                            <option value="香草">香草</option>
                            <option value="焦糖">焦糖</option>
                            <option value="巧克力">巧克力</option>
                            <option value="榛果">榛果</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label>数量</label>
                        <div class="quantity-control">
                            <button class="quantity-btn" id="decrease-btn">-</button>
                            <input type="number" id="quantity-input" class="quantity-input" value="1" min="1">
                            <button class="quantity-btn" id="increase-btn">+</button>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="order-note">备注信息</label>
                        <input type="text" id="order-note" placeholder="特殊要求或注意事项...">
                    </div>
                    <button class="btn btn-primary" id="order-btn">立即下单</button>
                </div>
            </div>
        </div>
    </div>
</div>

<!--添加咖啡模态框 -->
<div class="modal" id="add-coffee-modal">
    <div class="modal-content" style="max-width: 600px;">
        <div class="close-modal" id="close-add-modal">
            <i class="fas fa-times"></i>
        </div>

        <div class="coffee-detail" style="flex-direction: column;">
            <h2>添加新咖啡</h2>

            <div class="detail-image" id="coffee-image-upload"
                 style="height: 200px; cursor: pointer; background-color: #f8f9fa; border: 2px dashed #ccc;">
                <i class="fas fa-plus upload-icon"></i>
                <input type="file" id="coffee-image-input" accept="image/*" style="display: none;">
            </div>
            <div id="coffee-image-name" style="text-align: center; font-size: 12px; color: #666; margin-top: 5px;"></div>

            <div class="detail-info" style="width: 100%;">
                <form id="add-coffee-form">
                    <div class="form-group">
                        <label for="coffee-name">咖啡名称 *</label>
                        <input type="text" id="coffee-name" required>
                        <div class="error-text">请输入咖啡名称</div>
                    </div>

                    <div class="form-group">
                        <label for="coffee-category">分类 *</label>
                        <select id="coffee-category" required>
                            <option value="">请选择分类</option>
                            <option value="浓缩咖啡">浓缩咖啡</option>
                            <option value="拿铁">拿铁</option>
                            <option value="卡布奇诺">卡布奇诺</option>
                            <option value="美式咖啡">美式咖啡</option>
                            <option value="摩卡">摩卡</option>
                            <option value="冷萃">冷萃</option>
                            <option value="其他">其他</option>
                        </select>
                        <div class="error-text">请选择咖啡分类</div>
                    </div>

                    <div class="form-group">
                        <label for="coffee-price">价格（元）*</label>
                        <input type="number" id="coffee-price" min="0" step="0.01" required>
                        <div class="error-text">请输入有效的价格</div>
                    </div>

                    <div class="form-group">
                        <label for="coffee-description">描述</label>
                        <textarea id="coffee-description" rows="3" placeholder="咖啡的特点、口感描述..."></textarea>
                    </div>

                    <div style="display: flex; gap: 10px; margin-top: 20px;">
                        <button type="button" class="btn btn-outline" id="cancel-add-btn">取消</button>
                        <button type="submit" class="btn btn-primary">添加咖啡</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- 页脚 -->
<footer>
    <div class="container">
        <div class="footer-content">
            <div class="footer-column">
                <h3>关于我们</h3>
                <p>猫咖管理系统致力于为猫咪咖啡馆提供专业的管理解决方案，帮助店主高效管理猫咪、咖啡和顾客信息。</p>
            </div>

            <div class="footer-column">
                <h3>快速链接</h3>
                <ul class="footer-links">
                    <li><a href="index.html">首页</a></li>
                    <li><a href="cat.html">猫咪信息</a></li>
                    <li><a href="cafe.html">咖啡菜单</a></li>
                    <li><a href="">在线预订</a></li>
                    <li><a href="center.html">个人中心</a></li>
                </ul>
            </div>

            <div class="footer-column">
                <h3>联系方式</h3>
                <div class="contact-info">
                    <p><i class="fas fa-map-marker-alt"></i> 地址：广东科技学院</p>
                    <p><i class="fas fa-phone"></i> 电话：666666</p>
                    <p><i class="fas fa-envelope"></i> 邮箱：666666.com</p>
                    <p><i class="fas fa-clock"></i> 营业时间：10:00-18:00</p>
                </div>
            </div>
        </div>

        <div class="copyright">
            <p>© 2025 猫咖管理系统 版权所有 | 设计开发：会非的杨</p>
        </div>
    </div>
</footer>

<!-- 通知消息 -->
<div class="notification" id="notification"></div>

<script>
    // API端点配置
    const API_BASE_URL = 'http://localhost:8080/catcafe';
    const COFFEES_ENDPOINT = `${API_BASE_URL}/coffees`;
    const ORDERS_ENDPOINT = `${API_BASE_URL}/orders`;

    document.addEventListener('DOMContentLoaded', function () {
        const coffeesGrid = document.getElementById('coffees-grid');
        const searchInput = document.getElementById('search-input');
        const searchBtn = document.getElementById('search-btn');
        const resetBtn = document.getElementById('reset-btn');
        const categoryBtns = document.querySelectorAll('.category-btn');
        const loader = document.querySelector('.loader');
        const coffeeModal = document.getElementById('coffee-modal');
        const closeModal = document.getElementById('close-modal');
        const detailImage = document.getElementById('detail-image');
        const orderBtn = document.getElementById('order-btn');
        const notification = document.getElementById('notification');
        const decreaseBtn = document.getElementById('decrease-btn');
        const increaseBtn = document.getElementById('increase-btn');
        const quantityInput = document.getElementById('quantity-input');

        let currentCoffeeId = null;
        let activeCategory = 'all';

        const username = localStorage.getItem('username');
        const role = localStorage.getItem('role');
        // 获取显示用户信息的元素
        const userDisplay = document.getElementById('user-display');

        // 如果有用户信息，显示在导航栏
        if (username) {
            // 根据角色显示不同的文本
            const roleText = role === 'admin' ? '管理员' : '普通用户';
            userDisplay.textContent = `${roleText}：${username}`;

            // 添加角色图标和样式（可选）
            userDisplay.innerHTML = `            <i class="fas fa-user-circle"></i>
            <span class="username-text">${username}</span>
            <span class="role-badge">${roleText}</span>
        `;
        } else {
            userDisplay.textContent = "未登录";
        }

        // 退出按钮功能
        const logoutBtn = document.getElementById('logout-btn');
        logoutBtn.addEventListener('click', function () {
            // 清除存储的用户信息
            localStorage.removeItem('username');
            localStorage.removeItem('role');

            // 提示用户并跳转到登录页
            alert('您已成功退出');
            window.location.href = 'login.html'; // 替换为你的登录页面路径
        });

        // 显示加载动画
        function showLoader() {
            loader.style.display = 'block';
            coffeesGrid.innerHTML = '';
        }

        // 隐藏加载动画
        function hideLoader() {
            loader.style.display = 'none';
        }

        // 显示通知消息
        function showNotification(message, isSuccess = true) {
            notification.textContent = message;
            notification.className = `notification ${isSuccess ? 'success' : 'error'}`;
            setTimeout(() => {
                notification.style.opacity = '0';
                notification.style.transform = 'translateX(100%)';
            }, 3000);
        }

        // 获取所有咖啡信息
        function fetchCoffees() {
            showLoader();
            fetch(COFFEES_ENDPOINT)
                .then(response => {
                    if (!response.ok) throw new Error('网络响应失败');
                    return response.json();
                })
                .then(res => {
                    // 修改这里：code 是 1 表示成功
                    if (res.code === 1) {
                        renderCoffees(res.data);
                    } else {
                        throw new Error('接口返回异常: ' + res.msg || '未知错误');
                    }
                })
                .catch(error => {
                    console.error('获取咖啡失败:', error);
                    coffeesGrid.innerHTML = '<p class="no-results">加载咖啡数据失败，请检查网络或稍后再试</p>';
                })
                .finally(hideLoader);
        }



        // 根据名字搜索咖啡
        function searchCoffeesByName(name) {
            showLoader();
            fetch(`${COFFEES_ENDPOINT}/search?name=${encodeURIComponent(name)}`)
                .then(response => {
                    if (!response.ok) throw new Error('搜索失败');
                    return response.json();
                })
                .then(res => {
                    if (res.code === 1) {
                        renderCoffees(res.data);
                    } else {
                        throw new Error('搜索接口返回异常: ' + res.msg || '未知错误');
                    }
                })
                .catch(error => {
                    console.error('搜索失败:', error);
                    coffeesGrid.innerHTML = '<p class="no-results">搜索失败，请重试</p>';
                })
                .finally(hideLoader);
        }


        // 根据分类搜索咖啡
        function searchCoffeesByCategory(category) {
            if (category === 'all') {
                fetchCoffees();
                return;
            }
            showLoader();
            fetch(`${COFFEES_ENDPOINT}/category?category=${encodeURIComponent(category)}`)
                .then(response => {
                    if (!response.ok) throw new Error('分类搜索失败');
                    return response.json();
                })
                .then(res => {
                    if (res.code === 1) {
                        renderCoffees(res.data);
                    } else {
                        throw new Error('分类搜索接口返回异常: ' + res.msg || '未知错误');
                    }
                })
                .catch(error => {
                    console.error('分类搜索失败:', error);
                    coffeesGrid.innerHTML = '<p class="no-results">分类搜索失败，请重试</p>';
                })
                .finally(hideLoader);
        }


        // 获取单个咖啡详情
        function fetchCoffeeDetails(coffeeId) {
            fetch(`${COFFEES_ENDPOINT}/${coffeeId}`)
                .then(response => {
                    if (!response.ok) throw new Error('获取咖啡详情失败');
                    return response.json();
                })
                .then(res => {
                    if (res.code === 1) {
                        displayCoffeeDetails(res.data);
                    } else {
                        throw new Error('获取咖啡详情接口返回异常: ' + res.msg || '未知错误');
                    }
                })
                .catch(error => {
                    console.error('获取咖啡详情失败:', error);
                    showNotification('获取咖啡详情失败', false);
                });
        }


        // 提交订单
        function submitOrder(orderData) {
            fetch(ORDERS_ENDPOINT, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(orderData)
            })
                .then(response => {
                    if (!response.ok) throw new Error('网络响应失败');
                    return response.json();
                })
                .then(res => {
                    if (res.code === 1) {
                        showNotification('下单成功！订单号：' + res.data.orderNo, true);
                        closeCoffeeDetail();
                    } else {
                        throw new Error('接口返回异常: ' + res.msg || '未知错误');
                    }
                })
                .catch(error => {
                    console.error('下单失败:', error);
                    showNotification('下单失败，请重试', false);
                });
        }


        // 渲染咖啡列表
        function renderCoffees(coffees) {
            coffeesGrid.innerHTML = '';
            if (!coffees || coffees.length === 0) {
                coffeesGrid.innerHTML = '<p class="no-results">没有找到匹配的咖啡，请尝试其他搜索条件。</p>';
                return;
            }
            coffees.forEach(coffee => {
                const coffeeCard = document.createElement('div');
                coffeeCard.className = 'coffee-card';
                coffeeCard.innerHTML = `
                    <div class="coffee-image" style="background-image: url('${coffee.image}')">
                        <span class="coffee-price">¥${coffee.price}</span>
                    </div>
                    <div class="coffee-info">
                        <h3>${coffee.name}</h3>
                        <span class="coffee-category">${coffee.category}</span>
                        <p>${coffee.description}</p>
                    </div>`;
                coffeeCard.addEventListener('click', () => openCoffeeDetail(coffee.id));
                coffeesGrid.appendChild(coffeeCard);
            });
        }

        // 显示咖啡详情
        function displayCoffeeDetails(coffee) {
            currentCoffeeId = coffee.id;
            document.getElementById('detail-name').textContent = coffee.name;
            document.getElementById('detail-category').textContent = coffee.category;
            document.getElementById('detail-price').textContent = `¥${coffee.price}`;
            document.getElementById('detail-description').textContent = coffee.description;
            detailImage.style.backgroundImage = `url('${coffee.image}')`;

            document.getElementById('coffee-flavor').value = '';
            quantityInput.value = '1';
            document.getElementById('order-note').value = '';

            coffeeModal.style.display = 'block';
            document.body.style.overflow = 'hidden';
        }

        // 打开咖啡详情
        function openCoffeeDetail(coffeeId) {
            fetchCoffeeDetails(coffeeId);
        }

        // 关闭模态框
        function closeCoffeeDetail() {
            coffeeModal.style.display = 'none';
            document.body.style.overflow = 'auto';
            detailImage.classList.remove('zoomed');
        }

        // 图片放大功能
        detailImage.addEventListener('click', function () {
            this.classList.toggle('zoomed');
        });

        // 鼠标悬停放大功能
        detailImage.addEventListener('mousemove', function(e) {
            const rect = this.getBoundingClientRect();
            const x = e.clientX - rect.left;
            const y = e.clientY - rect.top;

            const scaleX = (x / rect.width) * 100;
            const scaleY = (y / rect.height) * 100;

            this.style.backgroundSize = '200% 200%';
            this.style.backgroundPosition = `${scaleX}% ${scaleY}%`;
        });

// 恢复原图比例
        detailImage.addEventListener('mouseleave', function() {
            this.style.backgroundSize = 'cover';
            this.style.backgroundPosition = 'center';
        });


        // 下单功能
        orderBtn.addEventListener('click', function () {
            const flavor = document.getElementById('coffee-flavor').value;
            const quantity = parseInt(quantityInput.value);
            const note = document.getElementById('order-note').value;

            if (!flavor) {
                showNotification('请选择咖啡口味', false);
                return;
            }

            if (isNaN(quantity) || quantity < 1) {
                showNotification('请选择正确的数量', false);
                return;
            }

            fetch(`${COFFEES_ENDPOINT}/${currentCoffeeId}`)
                .then(res => res.json())
                .then(data => {
                    if (data.code !== 1) throw new Error('获取咖啡信息失败'); // ✅ 修改这里
                    const coffee = data.data;
                    const total=coffee.price * quantity;
                    const orderData = {
                        coffeeId: currentCoffeeId,
                        name: coffee.name,
                        flavor: flavor,
                        quantity: quantity,
                        price: coffee.price,
                        total: total,
                        note: note || '无备注',
                        userId: localStorage.getItem('userId') || 'anonymous',
                        //date: new Date().toISOString().slice(0, 19).replace('T', ' ')
                    };
                    submitOrder(orderData);
                })
                    .catch(err => {
                    console.error('获取咖啡信息失败:', err);
                    showNotification('获取咖啡信息失败，请重试', false);
                });
        });

        // 数量控制
        decreaseBtn.addEventListener('click', function () {
            let qty = parseInt(quantityInput.value);
            if (qty > 1) quantityInput.value = qty - 1;
        });

        increaseBtn.addEventListener('click', function () {
            let qty = parseInt(quantityInput.value);
            quantityInput.value = qty + 1;
        });

        // 搜索按钮点击事件
        searchBtn.addEventListener('click', function () {
            const searchTerm = searchInput.value.trim();
            if (searchTerm) searchCoffeesByName(searchTerm);
            else fetchCoffees();
        });

        resetBtn.addEventListener('click', function () {
            searchInput.value = '';
            document.querySelectorAll('.category-btn').forEach(btn => btn.classList.remove('active'));
            document.querySelector('.category-btn[data-category="all"]').classList.add('active');
            activeCategory = 'all';
            fetchCoffees();
        });

        searchInput.addEventListener('keyup', function (e) {
            if (e.key === 'Enter') {
                const searchTerm = searchInput.value.trim();
                if (searchTerm) searchCoffeesByName(searchTerm);
            }
        });

        categoryBtns.forEach(btn => {
            btn.addEventListener('click', function () {
                document.querySelectorAll('.category-btn').forEach(b => b.classList.remove('active'));
                this.classList.add('active');
                const category = this.dataset.category;
                activeCategory = category;
                searchCoffeesByCategory(category);
            });
        });

        closeModal.addEventListener('click', closeCoffeeDetail);

        window.addEventListener('click', function (e) {
            if (e.target === coffeeModal && !detailImage.classList.contains('zoomed')) {
                closeCoffeeDetail();
            }
        });

        // 初始化页面 - 加载所有咖啡
        fetchCoffees();
    });

    // 获取新增咖啡相关元素
    const addCoffeeBtn = document.getElementById('add-coffee-btn');
    const addCoffeeModal = document.getElementById('add-coffee-modal');
    const closeAddModal = document.getElementById('close-add-modal');
    const cancelAddBtn = document.getElementById('cancel-add-btn');
    const coffeeImageUpload = document.getElementById('coffee-image-upload');
    const coffeeImageInput = document.getElementById('coffee-image-input');
    const coffeeImageNameDisplay = document.getElementById('coffee-image-name');
    const addCoffeeForm = document.getElementById('add-coffee-form');

    // 当前上传的图片文件
    let currentCoffeeImageFile = null;

    // 打开新增咖啡模态框
    addCoffeeBtn.addEventListener('click', () => {
        addCoffeeModal.style.display = 'block';
        document.body.style.overflow = 'hidden';
        // 重置表单
        addCoffeeForm.reset();
        currentCoffeeImageFile = null;
        coffeeImageUpload.innerHTML = '<i class="fas fa-plus upload-icon"></i>';
        coffeeImageNameDisplay.textContent = '';
        coffeeImageUpload.classList.remove('has-image');
    });

    // 关闭新增模态框
    function closeAddCoffeeModal() {
        addCoffeeModal.style.display = 'none';
        document.body.style.overflow = 'auto';
    }

    closeAddModal.addEventListener('click', closeAddCoffeeModal);
    cancelAddBtn.addEventListener('click', closeAddCoffeeModal);

    // 点击图片上传区域触发文件选择
    coffeeImageUpload.addEventListener('click', () => {
        coffeeImageInput.click();
    });

    // 处理图片选择
    coffeeImageInput.addEventListener('change', (e) => {
        const file = e.target.files[0];
        if (file) {
            // 检查文件类型
            if (!file.type.match('image.*')) {
                showNotification('请选择图片文件', false);
                return;
            }

            // 检查文件大小（限制2MB）
            if (file.size > 2 * 1024 * 1024) {
                showNotification('图片大小不能超过2MB', false);
                return;
            }

            currentCoffeeImageFile = file;

            // 显示预览
            const reader = new FileReader();
            reader.onload = (event) => {
                coffeeImageUpload.innerHTML = `<img src="${event.target.result}" alt="咖啡预览">`;
                coffeeImageUpload.classList.add('has-image');
                coffeeImageNameDisplay.textContent = file.name;
            };
            reader.readAsDataURL(file);
        }
    });

    // 表单验证函数
    function validateCoffeeForm() {
        let isValid = true;

        // 重置错误状态
        document.querySelectorAll('.form-group').forEach(group => {
            group.classList.remove('error');
        });

        // 检查必填字段
        const requiredFields = ['coffee-name', 'coffee-category', 'coffee-price'];
        requiredFields.forEach(id => {
            const field = document.getElementById(id);
            if (!field.value.trim()) {
                field.closest('.form-group').classList.add('error');
                isValid = false;
            }
        });

        // 验证价格是否为有效数字
        const priceField = document.getElementById('coffee-price');
        if (priceField.value && isNaN(parseFloat(priceField.value))) {
            priceField.closest('.form-group').classList.add('error');
            isValid = false;
        }

        return isValid;
    }

    // 提交新增咖啡表单
    addCoffeeForm.addEventListener('submit', (e) => {
        e.preventDefault();

        if (!validateCoffeeForm()) {
            showNotification('请填写所有必填字段', false);
            return;
        }

        // 收集表单数据
        const formData = new FormData();
        formData.append('name', document.getElementById('coffee-name').value);
        formData.append('category', document.getElementById('coffee-category').value);
        formData.append('price', document.getElementById('coffee-price').value);
        formData.append('description', document.getElementById('coffee-description').value);

        // 如果有图片，添加图片文件
        if (currentCoffeeImageFile) {
            formData.append('image', currentCoffeeImageFile);
        }

        // 显示加载状态
        const submitBtn = addCoffeeForm.querySelector('button[type="submit"]');
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 添加中...';
        submitBtn.disabled = true;

        // 发送POST请求到后端API
        fetch(`${API_BASE_URL}/coffees/add`, {
            method: 'POST',
            body: formData  // 注意：这里不需要设置Content-Type，浏览器会自动设置multipart/form-data
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('添加咖啡失败');
                }
                return response.json();
            })
            .then(data => {
                //showNotification('咖啡添加成功！', true);
                alert("咖啡添加成功！")
                location.reload()
                closeAddCoffeeModal();
                fetchCoffees(); // 刷新咖啡列表
            })
            .catch(error => {
                console.error('添加咖啡失败:', error);
                showNotification('添加咖啡失败，请重试', false);
            })
            .finally(() => {
                submitBtn.innerHTML = '添加咖啡';
                submitBtn.disabled = false;
            });
    });

</script>
</body>
</html>